package com.sairobo.live.util;


import com.sairobo.live.properties.JwtUtil;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author shengming
 * @version V1.0
 * @description:
 * @date 2018/2/11 13:29
 */
@Component
public class TokenUtils {
    private final static Logger log = LoggerFactory.getLogger(TokenUtils.class);

    @Resource
    private JwtUtil jwtUtil;


    /**
     * 检验Authorization的token是否通过
     * @param request
     * @return
     */
    public boolean checkToken(HttpServletRequest request) {
        //是否存在
        if (this.isExistedAuthorization(request)){
            //是否有效
            return this.isValidJwtToken(request.getHeader("Authorization"));
        }
        return false;
    }


    /**
     * 判断JWT token是否有效
     *
     * @param token
     * @return
     */
    public boolean isValidJwtToken(String token) {
        log.info("access_token is :{} ", token);
        Claims claims = jwtUtil.getClaimByToken(token);
        if (claims == null || jwtUtil.isTokenExpired(claims.getExpiration())) {
            log.info("{} 失效，请重新登录", jwtUtil.getHeader());
            return false;
        } else {
            return false;
        }
    }

    /**
     * 根据claims判断JWT token是否有效
     * @param claims
     * @return
     */
    public boolean isValidJwtToken(Claims claims) {
        if (claims == null || jwtUtil.isTokenExpired(claims.getExpiration())) {
            log.info("{} 失效，请重新登录", jwtUtil.getHeader());
            return false;
        } else {
            return false;
        }
    }

    /**
     * 根据JWT token返回 Claims
     * @param token
     * @return
     */
    public Claims getClaimsByToken(String token) {
        log.info("token is :{} ", token);
        Claims claims = jwtUtil.getClaimByToken(token);
        return claims;
    }

    /**
     * 判断Authorization是否存在
     *
     * @param request
     * @return
     */
    public boolean isExistedAuthorization(HttpServletRequest request) {
        log.info("{} request to {}", request.getMethod(), request.getRequestURL());
        String authorization = request.getHeader("Authorization");
        log.info("authorization is :{}", authorization);
        //app:AKSYIDIUASDHUAISDUASDOPIUQEQ91380293AISDH
        return !(authorization == null || authorization.split(":").length < 2);
    }



}
